# -*- coding: utf-8 -*-
import json
from datetime import datetime
from wechatApp.models import AccessToken
from wechatApi.token import refreshAccessToken

#获取wechat access token。先从数据库中查询，若不存在或已过期，则刷新token，并存入数据库
#若已存在且未过期，则直接返回token的access_token
def getToken():

	try:
		token = AccessToken.objects.get(id=1)

		duriation=datetime.now()-token.createDate
		if duriation.total_seconds()>=expires :
			#token 过期
			#调用api刷新token
			content=refreshAccessToken()
			token.accessToken=content['access_token']
			token.createDate=datetime.now()
			token.expires=content['expires_in']
			token.save()
	except Exception as e:
		#数据库中不存在，则获取token并存入数据库
		content=refreshAccessToken()
		AccessToken.objects.create(accessToken=content['access_token'],\
			expires=content['expires_in'],\
			createDate=datetime.now())

	return token.accessToken